<template>
    <div class="app-container" id='Admin'>
      <div class="filter-container" style="float: right;">
        <el-input v-model="listQuery.username" clearable class="filter-item" style="width: 200px;" placeholder="请输入管理员名称">
        </el-input>
        <el-button type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">查询</el-button>
        <el-button type="primary" class="filter-item" icon="el-icon-edit" @click="handleCreate">新增</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" border fit highlight-current-row>
        <el-table-column prop="id" align="center" label="管理员ID" sortable width="120">
        </el-table-column>
        <el-table-column prop="username" align="center" label="管理员名称" width="180">
        </el-table-column>
        <el-table-column prop="avatar" align="center" label="管理员图片">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="80">
          </template>
        </el-table-column>
        <el-table-column align="center" label="管理员角色" prop="roleIds">
          <template slot-scope="scope">
            <el-tag
            v-for="(item, index) in scope.row.roleIds"
            :key="index">{{ scope.row.roleIds | Status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="handleUpdate(scope.row)" type="primary" size="small">编辑</el-button>
            <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
        @pagination="getList" />
      <el-dialog :title="dialogStatus" :visible.sync="dialogFromVisible">
        <el-form ref="dataForm" :rules="rules" :model="dataForm"  label-width="100px" size="mini" style="width: 400px;margin-left: 20px;">
          <el-form-item label="管理员名称" prop="username">
            <el-input v-model="dataForm.username"></el-input>
          </el-form-item>
          <el-form-item label="管理员密码" prop="password">
            <el-input v-model="dataForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="管理员图片" prop="avatar">
            <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers"
              :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="dataForm.avatar" :src="dataForm.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="管理员角色" prop="roleIds">
            <el-select v-model="dataForm.roleIds" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFromVisible = false">取消</el-button>
          <el-button v-if="dialogStatus === '新增'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  <script>
    import Pagination from '@/components/Pagination'
    import {
      listAdmin,
      createAdmin,
      updateAdmin,
      deleteAdmin,
      roleOptions,
      uploadPath
    } from '@/api/system/admin'
    import {getToken} from '@/utils/auth'
    export default {
      name: 'Admin',
      components: {
        Pagination
      },
      computed: {
        headers(){
          return {'Shopping-Admin-Token':getToken()}
        }
      },
      data() {
        return {
          uploadPath,
          //查询数据
          listQuery: {
            page: 1,
            limit: 10,
            admin: '',
          },
          //总条数
          total: 0,
          //表格数据
          tableData: [],
          //添加或修改模态框状态
          dialogFromVisible: false,
          //模型框类型
          dialogStatus:'新增',
          //新增表单数据
          dataForm: {
            id: '',
            username: '',
            password: '',
            avatar: '',
            roleIds: [],
          },
          //获取用户角色字典值
          roleOptions: [],
          //校验规则
          rules: {
            username: [{required: true , message: '管理员名称不能为空',trigger:'blur'}],
            password: [{required: true , message: '管理员密码不能为空',trigger:'blur'}]
          }
        }
      },
      filters: {
        Status(Status) {
          if (Status == 1) { return "超级管理员" } 
          else if (Status == 2) { return "商场管理员" }
          else if (Status == 3) { return "推广管理员" }
         }
      },
      created() {
        // 数据初始化
        this.getList();
        this.getroleOptions();
      },
      methods: {
        //获取用户角色字典值
        getroleOptions(){
            roleOptions().then(res => {
                this.roleOptions = res.data.data.list;
            })
        },
        //查询列表
        handleFilter() {
          this.listQuery.page = 1;
          this.getList();
        },
        //获取列表数据接口
        getList() {
          listAdmin(this.listQuery).then(res => {
            console.log(res);
            this.tableData = [];
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;
          })
        },
        //重置表单数据
        resetForm(){
          this.dataForm = {
            id: '',
            username: '',
            password: '',
            avatar: '',
            roleIds: [],
          }
        },
        //打开新增模态框
        handleCreate() {
          this.resetForm();
          this.dialogStatus = '新增';
          this.dialogFromVisible = true;
        },
        //确定新增
        createData() {
          this.$refs['dataForm'].validate(valid => {
            if(valid){
              createAdmin(this.dataForm).then(res => {
                this.dialogFromVisible = false;
                this.getList();
                this.$notify.success({
                  title: '成功',
                  message: '新增成功'
                });
              }).catch(res => {
                this.$notify.error({
                  title: '失败',
                  message: res.data.errmsg
                });
              })
            }
          })
        },
        //打开修改模态框
        handleUpdate(row) {
          this.dataForm = Object.assign({}, row);
          this.dialogStatus = '修改';
          this.dialogFromVisible = true;
        },
        //确定修改
        updateData(){
          this.$refs['dataForm'].validate(valid => {
            if(valid){
              updateAdmin(this.dataForm).then(()=>{
                this.dialogFromVisible = false;
                this.getList();
                this.$notify.success({
                  title: '成功',
                  message: '修改成功'
                })
              }).catch(res => {
                this.$notify.error({
                  title: '失败',
                  message: res.data.errmsg
                });
              })
            }
          })
        },
        //删除
        handleDelete(row) {
          this.$confirm('此操作将删除该品牌商，是否继续？','提示',{
            confirmButtonText: '确定',
            concelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteAdmin(row).then(res => {
              this.getList();
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
            })
          }).catch(() => {
             this.$message({
               type: 'info',
               message: '已取消删除'
             })
          })
        },
        //图片上传成功后执行的方法
        handleAvatarSuccess(res, file) {
          this.dataForm.avatar = res.data.url
  
        },
        //图片上传成功前执行的方法
        beforeAvatarUpload(file) {
          // const isJPG = file.type === 'image/jpeg'; 
          // const isLt2M = file.size / 1024 / 1024 < 2;
          // if (!isJPG) {
          //   this.$message.error('上传头像图片只能是 JPG 格式!');
          // }
          // if (!isLt2M) {
          //   this.$message.error('上传头像图片大小不能超过 2MB!');
          // }
          // return isJPG && isLt2M;
        }
      }
    }
  
  </script>
  <style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  
  </style>
  <style scoped>
  </style>
  